package cn.e4j.modular.api.controller;

import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.InvokeUtil;
import cn.e4j.core.util.LocalDateUtils;
import cn.e4j.core.util.ToolUtil;
import cn.e4j.modular.api.mapper.QtpsMapper;
import cn.e4j.modular.api.service.QtpsService;
import cn.e4j.modular.api.util.CommonUtils;
import cn.e4j.modular.api.util.ControllerSupport;
import cn.e4j.modular.crm.entity.*;
import cn.e4j.modular.crm.mapper.GwakTMapper;
import cn.e4j.modular.crm.mapper.GwaklTMapper;
import cn.e4j.modular.crm.mapper.GwamTMapper;
import cn.e4j.modular.crm.mapper.GwcsTMapper;
import cn.e4j.modular.system.entity.SysUser;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("api/wx/qtps")
public class QtpsController extends ControllerSupport {
    @Autowired
    GwaklTMapper gwaklTMapper;

    @Autowired
    GwakTMapper gwakTMapper;

    @Autowired
    GwamTMapper gwamTMapper;

    @Autowired
    QtpsService qtpsService;

    @Autowired
    GwcsTMapper gwcsTMapper;

    public static ResponseData SUCCESS(Object obj){
        return new SuccessResponseData(obj);
    }

    @RequestMapping("getCompany")
    public ResponseData getCompany(@DtoParam DtoWapper wapper){
        Dto inDto = wapper.getDto();
        List<Dto> list = new ArrayList<>();
        SysUser user = wapper.getSysUser();
        try {
            inDto.put("GWCUUSER",user.getID());
            inDto.put("GWCUENT",inDto.getString("ENT"));
            list = qtpsService.getCompany(inDto);
        }catch (Exception e){
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS(list);
    }

    @RequestMapping("getBusinessmen")
    public ResponseData getBusinessmen(@DtoParam DtoWapper wapper){
        Dto inDto = wapper.getDto();
        List<Dto> list = new ArrayList<>();
        try {
//            "cn.e4j.modular.api.mapper.QtpsMapper.getBusinessmen"
//            list = InvokeUtil.invokeBeanMethod("qtpsMapper,getBusinessmen",wapper.getPage(),inDto);
            list = InvokeUtil.invokeBeanMethod2("cn.e4j.modular.api.mapper.QtpsMapper.getBusinessmen",wapper.getPage(),inDto);
        }catch (Exception e){
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS(list);
    }

    @RequestMapping("check")
    public ResponseData getOrderNum(@DtoParam DtoWapper wapper){
        Dto inDto = wapper.getDto();
        Dto outDto = new Dto();
        SysUser currentUser = wapper.getSysUser();
        try {
            String customerNo = inDto.getString("customerNo");
            Integer validateProductNoInKC = qtpsService.validateProductNoInKC(inDto);
            Integer validCustomerNo = qtpsService.validCustomerNo(inDto);
            Integer ifPurchaseProduct = qtpsService.ifPurchaseProduct(inDto);
            outDto.put("customerNoIsValid",(validCustomerNo!=null && validCustomerNo>0)?true:false);//客户编号是否有效
            outDto.put("ProductNoIsInKC",(validateProductNoInKC!=null && validateProductNoInKC>0)?true:false);
            outDto.put("ifPurchaseProduct",(ifPurchaseProduct!=null && ifPurchaseProduct>0)?true:false);//是否在mmra_t中
            if (!outDto.getBoolean("ProductNoIsInKC") || !outDto.getBoolean("customerNoIsValid") || outDto.getBoolean("ifPurchaseProduct"))
                return SUCCESS(outDto);

            List<Dto> detail = qtpsService.getDetail(inDto);

            QueryWrapper<GwaklT> gwaklTQueryWrapper = new QueryWrapper<>();
            gwaklTQueryWrapper.eq("GWAKLENT",inDto.getString("ENT"));
            gwaklTQueryWrapper.eq("GWAKL001",customerNo);
            GwaklT po = gwaklTMapper.selectOne(gwaklTQueryWrapper);

            outDto.put("customerName",po==null?"":po.getGWAKL003());
            if (detail!=null && detail.size()>0){
                Dto dto = detail.get(0);
                outDto.put("productName",(dto==null || ToolUtil.isEmpty(dto.getString("GWAML003"))?"-":dto.getString("GWAML003")));
                outDto.put("spec",(dto==null || ToolUtil.isEmpty(dto.getString("GWAML004"))?"-":dto.getString("GWAML004")));
            }

            //获取订单号gwcs_t
            QueryWrapper<GwcsT> query = new QueryWrapper<>();
            query.eq("GWCS001",inDto.getString("productNo"));
            query.eq("GWCS010",customerNo);
            query.eq("GWCS019",inDto.getString("seqNo"));
            GwcsT gwcsTPO = gwcsTMapper.selectOne(query);

            outDto.put("GWCSDOCNO","");
            outDto.put("GWCS002","");

            if (gwcsTPO!=null){
                outDto.put("GWCSDOCNO",gwcsTPO.getGWCSDOCNO());
                outDto.put("GWCS002",gwcsTPO.getGWCS002());
            }

            //1、微信端提交成功后，写入mmra_t中时“设备销售方”没有给值，应该是根据客户资料档默认的归属法人（gwakplant）存入
            //2、“业务员姓名”和“业务员手机”号码没有存入，默认微信端操作者对应的用户ID和手机号码
            QueryWrapper<GwakT> gwakTQueryWrapper = new QueryWrapper<>();
            gwakTQueryWrapper.eq("GWAKENT",inDto.getString("ENT"));
            gwakTQueryWrapper.eq("GWAK001",customerNo);
            GwakT gwak_tPO = gwakTMapper.selectOne(gwakTQueryWrapper);
            outDto.put("GWAKPLANT",gwak_tPO.getGWAKPLANT());
//            outDto.put("GWCS014",currentUser.getID());//业务员
//            outDto.put("GWCS015",currentUser.getMOBILE());//业务员手机

        }catch (Exception e){
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS(outDto);
    }

    @RequestMapping("save")
    public ResponseData save(@DtoParam DtoWapper wapper){
        Dto inDto = wapper.getDto();
        Dto outDto = new Dto();
        SysUser user = wapper.getSysUser();
        LocalDate now = LocalDate.now();
        try {
            JSONArray list = JSONArray.parseArray(inDto.getString("list"));

            List<GwcuT> seqList = getSeqList(list, user);
            List<MmraT> mmraTPOS = new ArrayList<>();
            for (int i=0;i<seqList.size();i++){
                JSONObject jsonObject = list.getJSONObject(i);
                GwcuT gwcu = seqList.get(i);

                gwcu.setGWCU003(jsonObject.getString("GWCS002"));//set销售单位
                //客户设备档
                MmraT po = new MmraT();
                po.setMMRAENT(user.getDBC());
                po.setMMRA001(jsonObject.getString("GWCS010"));
                po.setMMRA002(gwcu.getGWCU001());
                po.setMMRA003(gwcu.getGWCU002());
                po.setMMRA004(jsonObject.getString("productName"));
                //获取设备类型
                QueryWrapper<GwamT> gwamTQueryWrapper = new QueryWrapper<>();
                gwamTQueryWrapper.eq("GWAM001", po.getMMRA002());
                GwamT gwam = gwamTMapper.selectOne(gwamTQueryWrapper);
                po.setMMRA007(ToolUtil.isNotEmpty(gwam)?gwam.getGWAM007():"-");
                po.setMMRA009(jsonObject.getString("ERPOrderNo"));
                po.setMMRA010(now);
                po.setMMRA011(now);
                po.setMMRA013("1");
                po.setMMRA014("1");
                po.setMMRA017(jsonObject.getString("GWAKPLANT"));
                po.setMMRA006(jsonObject.getString("spec"));//规格
                String gwam012 = (gwam==null || gwam.getGWAM012()==null?"0":gwam.getGWAM012());//保固月数
                String gwam013 = (gwam==null || gwam.getGWAM013()==null?"0":gwam.getGWAM013());//保固天数
                Date varDate = DateUtils.addMonths(new Date(),Integer.parseInt(gwam012));
                Date threeDays = DateUtils.addDays(varDate, Integer.parseInt(gwam013));
                po.setMMRA012(LocalDateUtils.dateToLocalDate(threeDays));//三包到期日期计算
                po.setMMRAACTI("Y");
                po.setMMRAUSER(user.getACCOUNT());
                po.setMMRAGRUP(user.getORG_ID());
                po.setMMRATIME(DateUtils.getTime());
                po.setMMRADATE(now);

                //添加业务员信息
//                po.setMMRA042(jsonObject.getString("GWCS014"));
//                po.setMMRA043(jsonObject.getString("GWCS015"));
                po.setMMRA042(jsonObject.getString("businessId"));
                po.setMMRA043(jsonObject.getString("businessMOBILE"));

                mmraTPOS.add(po);
            }
            qtpsService.save(seqList,mmraTPOS);

            inDto.put("GWCUUSER",user.getID());
            inDto.put("GWCUENT", inDto.getString("ENT"));
            outDto.put("selectList",qtpsService.getCompany(inDto));

        }catch (Exception e){
            e.printStackTrace();
            return ERROR;
        }

        return SUCCESS(outDto);
    }

    //将多个品类的单子设置项序,并返回处理后的list
    private List<GwcuT> getSeqList(JSONArray list,SysUser user) {
        String temp = "";
        List<GwcuT> gwcuts = new ArrayList<>();
        Date date = new Date();
        for (int i = 0;i<list.size();i++){
            Dto queryDto = new Dto();
            JSONObject jsonObject = list.getJSONObject(i);
//            Integer count = jsonObject.getInteger("count");
            String productNo = jsonObject.getString("productNo");
            String orderNo = jsonObject.getString("orderNo");

            queryDto.put("productNo",productNo);
            queryDto.put("orderNo",orderNo);
            Integer maxSeq = qtpsService.getMaxSeq(queryDto);
            maxSeq = (maxSeq == null?0:maxSeq);

            temp +=(productNo+",");
            Integer seq = temp.split(productNo).length;
            jsonObject.put("GWCUSEQ",maxSeq+seq);


            GwcuT gwcuTPO = CommonUtils.toJavaClass(jsonObject,GwcuT.class);
            gwcuTPO.setGWCUDOCNO("YSDH" + DateUtils.getDate("yyyyMMddHHmmssSSS"));
            gwcuTPO.setGWCUENT(user.getDBC());
            //gwcuTPO.setGWCUDOCDATE(date);
            gwcuTPO.setGWCUDOCDATE(LocalDate.now());
            gwcuTPO.setGWCUUSER(user.getID());
            gwcuTPO.setGWCUGRUP(user.getORG_ID());
            gwcuTPO.setGWCUDATE(LocalDate.now());
            gwcuTPO.setGWCUTIME(DateUtils.formatDate(date, "HH:mm:ss"));
            gwcuTPO.setGWCUORIG(user.getORG_ID());
            gwcuTPO.setGWCUORIU(user.getID());
            gwcuTPO.setGWCUACTI("N");
            gwcuts.add(gwcuTPO);
        }

        return gwcuts;
    }

}
